﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TinyTeam.UI;

public class MyJoystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IEndDragHandler
{
    public static MyJoystick instance;

    public Image dayuan;
    public Image xiaoyuan;

    public Vector2 direction;

    void Awake()
    {
        instance = this;
    }
    // Use this for initialization
    void Start()
    {
        dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 0.3f);
        xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 0.3f);
    }

    private void MyPress(Vector2 v2)
    {
        Vector2 shouzhiPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(TTUIRoot.Instance.GetComponent<Canvas>().transform as RectTransform, v2, TTUIRoot.Instance.GetComponent<Canvas>().worldCamera, out shouzhiPos);
        float dis = Vector3.Distance(shouzhiPos, dayuan.transform.localPosition);
        dis = Mathf.Clamp(dis, 0, dayuan.rectTransform.rect.width / 2);

        Vector3 shouzhiV3 = shouzhiPos;

        Vector3 dir = (shouzhiV3 - dayuan.transform.localPosition).normalized;
        xiaoyuan.transform.localPosition = dayuan.transform.localPosition + dir * dis;

        direction = dir * dis / (dayuan.rectTransform.rect.width / 2);

        dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 1);
        xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 1);
    }

    private void MyUp()
    {
        xiaoyuan.transform.localPosition = dayuan.transform.localPosition;
        dayuan.color = new Color(dayuan.color.r, dayuan.color.g, dayuan.color.b, 0.3f);
        xiaoyuan.color = new Color(xiaoyuan.color.r, xiaoyuan.color.g, xiaoyuan.color.b, 0.3f);
        direction = Vector2.zero;
    }

    public void MyEndDrag()
    {
        MyUp();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        MyPress(eventData.pressPosition);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        MyUp();
    }

    public void OnDrag(PointerEventData eventData)
    {
        MyPress(eventData.position);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        MyUp();
    }

}
